package com.sz.app.oss.api.logistics.base;

import com.sz.app.oss.constants.MessagesCodes;
import com.sz.app.oss.constants.Permissions;
import com.sz.app.oss.exception.ErrorCodes;
import com.sz.biz.app.web.BaseController;
import com.sz.biz.logistics.constants.ServiceConstants;
import com.sz.biz.logistics.core.dto.ServiceCargoDto;
import com.sz.biz.logistics.core.dto.ServiceClassDto;
import com.sz.biz.logistics.core.dto.ServiceDto;
import com.sz.biz.logistics.core.dto.ServiceRegionObjDto;
import com.sz.biz.logistics.core.entity.ServiceRegionRel;
import com.sz.biz.logistics.core.service.ServiceCargoTypeRelService;
import com.sz.biz.logistics.core.service.ServiceClassRelService;
import com.sz.biz.logistics.core.service.ServiceRegionRelService;
import com.sz.biz.logistics.core.service.ServiceService;
import com.sz.common.base.dto.QueryParams;
import com.sz.common.base.dto.ResultDto;
import com.sz.common.base.exception.BizException;
import com.sz.common.base.exception.Exceptions;
import com.sz.common.base.utils.StringUtils;
import com.sz.common.core.service.PrincipalUtils;
import com.sz.common.core.system.service.SysUserSupport;
import com.sz.common.core.system.service.UserModel;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.text.ParseException;
import java.util.Arrays;
import java.util.List;

/**
 * Function: ServiceController <br>
 * Author: wentao.chang <br>
 * Date: 2016-11-28 14:20:00
 */
@RestController
@RequestMapping("${api}/biz/services")
@Api(description = " ", tags = "032、服务管理")
public class ServiceController extends BaseController {

    @Autowired
    private SysUserSupport userSupport;
    @Autowired
    private ServiceService serviceService;
    @Autowired
    private ServiceRegionRelService serviceRegionRelService;
    @Autowired
    private ServiceClassRelService serviceClassRelService;
    @Autowired
    private ServiceCargoTypeRelService serviceCargoTypeRelService;

    @ApiOperation(value = "新建服务", notes = "-<br>权限：" + Permissions.BIZ_MGT_BASE_SERVICE)
    @ApiImplicitParams({@ApiImplicitParam(name = "serviceDto", value = "提交的服务信息\r\n "
            + "name,code,description,\r\nserviceTypeCodes[整型数组],serviceAreas\r\n" +
            "[type,country,areaId,startPostcode,endPostcode]\r\n" +
            "cargoTypes[cargoTypeCode],", required = true, dataType = "ServiceDto", paramType = "body")})
    @RequestMapping(value = "", method = RequestMethod.POST)
    @RequiresPermissions(value = {Permissions.BIZ_MGT_BASE_SERVICE})
    public ResultDto saveService(@RequestBody ServiceDto serviceDto) throws ParseException {
        int userId = PrincipalUtils.getAccountId();
        serviceDto.setCreateUserId(userId);
        serviceDto.setLastUpdateUserId(userId);
        String uid = serviceService.save(serviceDto);
        ResultDto resultDto = getSaveSuccessDto(MessagesCodes.MODULE_SERVICE);
        resultDto.setData(uid);
        return resultDto;
    }


    @ApiOperation(value = "查询服务范围", notes = "查询服务范围<br>权限：" + Permissions.BIZ_MGT_BASE_SERVICE)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "服务的id ", required = true, dataType = "Integer", paramType = "path")})
    @RequestMapping(value = "/{id}/region", method = {RequestMethod.GET})
    public ResultDto getRegionByServiceId(@PathVariable Integer id) {
        List<ServiceRegionRel> regionList = serviceRegionRelService.findByServiceId(id);
        ResultDto dto = new ResultDto();
        dto.setData(regionList);
        return dto;
    }

    @ApiOperation(value = "添加服务范围信息", notes = "添加服务范围信息<br>权限：" + Permissions.BIZ_MGT_BASE_SERVICE)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "serviceRegionRel", value = "添加服务范围信息\r\n "
                    + "serviceId, type(取值：s/e), remark", required = true, dataType = "ServiceRegionRel", paramType = "body")})
    @RequestMapping(value = "/region", method = {RequestMethod.POST})
    @RequiresPermissions(value = {Permissions.BIZ_MGT_BASE_SERVICE, Permissions.BIZ_MGT_BASE_SERVICE_APPROVAL}, logical = Logical.OR)
    public
    @ResponseBody
    ResultDto addServiceRegion(@RequestBody ServiceRegionRel serviceRegionRel) throws ParseException {
        String uid = serviceRegionRelService.save(serviceRegionRel);
        ResultDto dto = this.getSaveSuccessDto(MessagesCodes.MODULE_SERVICE_REGION);
        dto.setData(uid);
        return dto;
    }

    @ApiOperation(value = "修改干线服务范围信息", notes = "修改干线服务范围信息<br>权限：" + Permissions.BIZ_MGT_BASE_SERVICE)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "serviceClassDto", value = "添加干线服务范围信息\r\n "
                    + "lineId, classId[]", required = true, dataType = "ServiceClassDto", paramType = "body")})
    @RequestMapping(value = "/{uid}/classes", method = {RequestMethod.POST})
    @RequiresPermissions(value = {Permissions.BIZ_MGT_BASE_SERVICE, Permissions.BIZ_MGT_BASE_SERVICE_APPROVAL}, logical = Logical.OR)
    public
    @ResponseBody
    ResultDto addServiceRegion(@PathVariable String uid, @RequestBody ServiceClassDto serviceClassDto) throws ParseException {
        serviceClassRelService.save(uid, serviceClassDto);
        ResultDto dto = this.getSaveSuccessDto(MessagesCodes.MODULE_SERVICE_REGION);
        dto.setData(uid);
        return dto;
    }

    @ApiOperation(value = "修改服务范围信息", notes = "修改服务范围信息<br>权限：" + Permissions.BIZ_MGT_BASE_SERVICE)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "服务范围的id ", required = true, dataType = "Integer", paramType = "path"),
            @ApiImplicitParam(name = "serviceRegionRel", value = "提交服务范围信息\r\n "
                    + "serviceId, type(取值：s/e), remark", required = true, dataType = "ServiceRegionRel", paramType = "body")})
    @RequestMapping(value = "/{id}/region", method = {RequestMethod.PUT})
    @RequiresPermissions(value = {Permissions.BIZ_MGT_BASE_SERVICE, Permissions.BIZ_MGT_BASE_SERVICE_APPROVAL}, logical = Logical.OR)
    public
    @ResponseBody
    ResultDto updateServiceRegion(@PathVariable Integer id, @RequestBody ServiceRegionRel serviceRegionRel) throws ParseException {
        serviceRegionRel.setId(id);
        String newUid = serviceRegionRelService.update(serviceRegionRel);
        ResultDto dto = this.getUpdateSuccessDto(MessagesCodes.MODULE_SERVICE_REGION);
        dto.setData(newUid);
        return dto;
    }

    @ApiOperation(value = "删除服务范围信息", notes = "删除服务范围信息<br>权限：" + Permissions.BIZ_MGT_BASE_SERVICE)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "ids", value = "服务范围关联的id ", required = true, dataType = "List", paramType = "body")})
    @RequestMapping(value = "/region/deletions", method = {RequestMethod.POST})
    @RequiresPermissions(value = {Permissions.BIZ_MGT_BASE_SERVICE, Permissions.BIZ_MGT_BASE_SERVICE_APPROVAL}, logical = Logical.OR)
    public
    @ResponseBody
    ResultDto deleteServiceRegion(@RequestBody List<Integer> ids) throws ParseException {
        serviceRegionRelService.batchDeleteById(ids);
        return this.getDeleteSuccessDto(MessagesCodes.MODULE_SERVICE_REGION);
    }

    @ApiOperation(value = "修改服务", notes = "-<br>权限：" + Permissions.BIZ_MGT_BASE_SERVICE)
    @ApiImplicitParams({
            @ApiImplicitParam(
                    name = "uid", value = "修改服务的uid", required = true, dataType = "string", paramType = "path"),
            @ApiImplicitParam(name = "serviceDto", value = "提交的服务信息\r\n "
                    + "同新增", required = true, dataType = "ServiceDto", paramType = "body")})
    @RequestMapping(value = "/{uid}", method = RequestMethod.PUT)
    @RequiresPermissions(value = {Permissions.BIZ_MGT_BASE_SERVICE})
    public ResultDto updateServiceMain(@PathVariable String uid, @RequestBody ServiceDto serviceDto) throws ParseException {
        serviceDto.setLastUpdateUserId(PrincipalUtils.getAccountId());
        serviceService.update(uid, serviceDto, false);
        ResultDto resultDto = getUpdateSuccessDto(MessagesCodes.MODULE_SERVICE);
        resultDto.setData(uid);
        return resultDto;
    }


    @ApiOperation(value = "按uid获取一个服务", notes = "-")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "uid", value = "服务的uid ", required = true, dataType = "uid", paramType = "path")})
    @RequestMapping(value = "/{uid}", method = RequestMethod.GET)
    public ResultDto findServiceById(@PathVariable String uid) {
        ServiceDto dto = serviceService.findDtoActivedByUid(uid);
        if (null != dto && dto.getCreateUserId() != null) {
            UserModel ud = userSupport.getUserById(dto.getCreateUserId());
            if (ud != null) {
                dto.setUserName(ud.getFullName() + " " + ud.getAccountName());
            }
        }
        ResultDto resultDto = new ResultDto();
        resultDto.setData(dto);
        return resultDto;
    }

    @ApiOperation(value = "按uid获取服务的范围(航班 船次 国家地区)", notes = "-")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "uid", value = "服务的uid ", required = true, dataType = "uid", paramType = "path")})
    @RequestMapping(value = "/{uid}/regions", method = RequestMethod.GET)
    public ResultDto findServiceRegionsByUid(@PathVariable String uid) {
        ServiceRegionObjDto dto = serviceService.findServiceRegionsByUid(uid);

        ResultDto resultDto = new ResultDto();
        resultDto.setData(dto);
        return resultDto;
    }

    @ApiOperation(value = "按uid获取服务的货物类型", notes = "-")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "uid", value = "服务的uid ", required = true, dataType = "uid", paramType = "path")})
    @RequestMapping(value = "/{uid}/cargos", method = RequestMethod.GET)
    public ResultDto findServiceCargotypesByUid(@PathVariable String uid) {
        List<ServiceCargoDto> dto = serviceCargoTypeRelService.findCargosByServiceUid(uid);

        ResultDto resultDto = new ResultDto();
        resultDto.setData(dto);
        return resultDto;
    }

    @ApiOperation(value = "提交审核服务", notes = "-")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "uids", value = "服务的uid ", required = true, dataType = "String[]", paramType = "body")})
    @RequestMapping(value = "/submit", method = RequestMethod.POST)
    @RequiresPermissions(value = {Permissions.BIZ_MGT_BASE_SERVICE})
    public ResultDto submit(@RequestBody List<String> uids) throws ParseException {
        serviceService.submit(uids);
        ResultDto resultDto = getSubmitSuccessDto(MessagesCodes.MODULE_SERVICE);
        return resultDto;
    }


    @ApiOperation(value = "获取服务列表", notes = "获取服务列表，返回服务列表，支持分页")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "serviceTypeCode", value = "类型id -1表示全部",
                    required = true, dataType = "string", paramType = "path"),
            @ApiImplicitParam(name = "q", value = "查询的关键字", dataType = "string", paramType = "query"),
            //@ApiImplicitParam(name = "productUid", value = "产品uid", dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "status", value = "状态：-1全部(默认) -2审核列表的全部 1草稿 2提交审核 3审核通过 4已启用 5已停用",
                    dataType = "int", paramType = "query"),
            @ApiImplicitParam(name = "includeAllAudit", value = "仅当status为3时，是否包含审核以上的状态",
                    dataType = "boolean", paramType = "query"),
            @ApiImplicitParam(name = "orderby", value = "排序字段:草稿列表createtime(默认) 待审核列表submittime",
                    dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "pageIndex", value = "分页 默认第一页", dataType = "int", paramType = "query"),
            @ApiImplicitParam(name = "pageSize", value = "页面大小", dataType = "int", paramType = "query"),
            @ApiImplicitParam(name = "asc", value = "排序方式", dataType = "boolean", paramType = "query", defaultValue = "true")})
    @RequestMapping(value = "/search/{serviceTypeCode}", method = {RequestMethod.GET})
    public ResultDto getServices(@PathVariable String serviceTypeCode,
                                 //@RequestParam(required = false, defaultValue = "") String productUid,
                                 @RequestParam(required = false, defaultValue = "") String q,
                                 @RequestParam(required = false, defaultValue = "-1") int status,
                                 @RequestParam(required = false, defaultValue = "false") boolean includeAllAudit,
                                 @RequestParam(required = false, defaultValue = "createtime") String orderby,
                                 @RequestParam(required = false, defaultValue = "1") int pageIndex,
                                 @RequestParam(required = false, defaultValue = "10") int pageSize,
                                 @RequestParam(required = false) String sort,
                                 @RequestParam(required = false, defaultValue = "true") Boolean asc)
            throws BizException {
        q = StringUtils.replaceSqlPattern(q);
        QueryParams params = new QueryParams(pageSize, pageIndex, q, sort, asc);
        params.put("serviceTypeCode", serviceTypeCode);
        int realIsOnline = -1;
        int realStatus = -1;
        if (status == ServiceConstants.Status.ALL) {
            realIsOnline = -1;
            realStatus = -1;
        }
        if (status == ServiceConstants.Status.AUDIT_ALL) {
            realIsOnline = -1;
            realStatus = 3;
        }
        if (status == ServiceConstants.Status.DRAFTS ||
                status == ServiceConstants.Status.PENDING_AUDIT ||
                status == ServiceConstants.Status.AUDIT_PASS) {
            realIsOnline = -2;
            realStatus = status;
        }
        if (status == ServiceConstants.Status.ENABLED) {
            realStatus = 3;
            realIsOnline = 1;
        }
        if (status == ServiceConstants.Status.DISABLE) {
            realStatus = 3;
            realIsOnline = 0;
        }
        if (status == ServiceConstants.Status.AUDIT_PASS && includeAllAudit) {
            realIsOnline = -1;
        }
        params.put("isOnline", realIsOnline);
        params.put("status", realStatus);
        params.put("fromShort", false);

        params.put("orderby", orderby);
        params.put("asc", asc);
        return serviceService.findByFilter(params);
    }

    @ApiOperation(value = "获取服务列表", notes = "获取服务列表，返回服务列表，支持分页")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "serviceTypeCode", value = "类型id -1表示全部",
                    required = true, dataType = "string", paramType = "path"),
            @ApiImplicitParam(name = "q", value = "查询的关键字", dataType = "string", paramType = "query"),
            //@ApiImplicitParam(name = "productUid", value = "产品uid", dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "status", value = "状态：-1全部(默认) -2审核列表的全部 1草稿 2提交审核 3审核通过 4已启用 5已停用",
                    dataType = "int", paramType = "query"),
            @ApiImplicitParam(name = "includeAllAudit", value = "仅当status为3时，是否包含审核以上的状态",
                    dataType = "boolean", paramType = "query"),
            @ApiImplicitParam(name = "orderby", value = "排序字段:草稿列表createtime(默认) 待审核列表submittime",
                    dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "pageIndex", value = "分页 默认第一页", dataType = "int", paramType = "query"),
            @ApiImplicitParam(name = "pageSize", value = "页面大小", dataType = "int", paramType = "query")})
    @RequestMapping(value = "/search/short/{serviceTypeCode}", method = {RequestMethod.GET})
    public ResultDto getShortServices(@PathVariable String serviceTypeCode,
                                      @RequestParam(required = false, defaultValue = "") String q,
                                      @RequestParam(required = false, defaultValue = "3") int status,
                                      @RequestParam(required = false, defaultValue = "true") boolean includeAllAudit,
                                      @RequestParam(required = false, defaultValue = "createtime") String orderby,
                                      @RequestParam(required = false, defaultValue = "1") int pageIndex,
                                      @RequestParam(required = false, defaultValue = "10") int pageSize)
            throws BizException {
        q = StringUtils.replaceSqlPattern(q);
        QueryParams params = new QueryParams(pageSize, pageIndex, q, null);
        params.put("serviceTypeCode", serviceTypeCode);
        int realIsOnline = -1;
        int realStatus = -1;
        if (status == ServiceConstants.Status.ALL) {
            realIsOnline = -1;
            realStatus = -1;
        }
        if (status == ServiceConstants.Status.AUDIT_ALL) {
            realIsOnline = -1;
            realStatus = 3;
        }
        if (status == ServiceConstants.Status.DRAFTS ||
                status == ServiceConstants.Status.PENDING_AUDIT ||
                status == ServiceConstants.Status.AUDIT_PASS) {
            realIsOnline = -2;
            realStatus = status;
        }
        if (status == ServiceConstants.Status.ENABLED) {
            realStatus = 3;
            realIsOnline = 1;
        }
        if (status == ServiceConstants.Status.DISABLE) {
            realStatus = 3;
            realIsOnline = 0;
        }
        if (status == ServiceConstants.Status.AUDIT_PASS && includeAllAudit) {
            realIsOnline = -1;
        }
        params.put("isOnline", realIsOnline);
        params.put("status", realStatus);
        params.put("orderby", orderby);
        params.put("fromShort", true);
        return serviceService.findByFilter(params);
    }

    /**
     * 批量删除服务
     *
     * @throws Exception
     */
    @ApiOperation(value = "批量删除服务", notes = "非物理删除 打标志 <br>权限：" + Permissions.BIZ_MGT_BASE_SERVICE)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "uids", value = "服务的ids",
                    required = true, dataType = "array", paramType = "body")})
    @RequestMapping(value = "/deletions", method = {RequestMethod.POST})
    @RequiresPermissions(value = {Permissions.BIZ_MGT_BASE_SERVICE})
    public ResultDto deleteServices(@RequestBody String[] uids) throws Exception {
        if (uids == null || uids.length == 0) {
            throw Exceptions.bizException(ErrorCodes.ERROR_ARGUMENT_EMPTY, "uids");
        }
        serviceService.batchdelete(Arrays.asList(uids));
        ResultDto dto = getDeleteSuccessDto(MessagesCodes.MODULE_SERVICE);
        return dto;
    }

    //异步校验

    /**
     * 异步校验服务编码
     */
    @ApiOperation(value = "异步校验服务编码", notes = "异步校验服务编码")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "code", value = "服务编码",
                    required = true, dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "uid", value = "服务uid 修改时传uid 新增时传空",
                    dataType = "string", paramType = "query")})
    @RequestMapping(value = "/checkcode", method = {RequestMethod.GET})
    public ResultDto codeCheck(@RequestParam String code,
                               @RequestParam(required = false, defaultValue = "0") String uid) {
        serviceService.codeCheck(uid, code);
        return new ResultDto();
    }

    /**
     * 异步校验服务名称
     */
    @ApiOperation(value = "异步校验服务名称", notes = "异步校验服务名称")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "name", value = "服务名称",
                    required = true, dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "uid", value = "服务uid 修改时传uid 新增时传空",
                    dataType = "string", paramType = "query")})
    @RequestMapping(value = "/checkname", method = {RequestMethod.GET})
    public ResultDto supplierNameCheck(@RequestParam String name,
                                       @RequestParam(required = false, defaultValue = "0") String uid) {
        serviceService.nameCheck(uid, name);
        return new ResultDto();
    }


}
